package com.qf.iprate.filter;

import com.qf.iprate.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import java.io.IOException;

@Component
@Slf4j
public class BlackListFilter implements Filter {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String ip = request.getRemoteAddr();
        log.info("请求进入过滤器了，请求的ip地址为:{}",ip);

        // 检查一下ip地址是否在黑名单中，如果在，则请求到此为止
        String key = Constants.IP_BLACKLIST_KEY;
        Boolean flag = redisTemplate.opsForSet().isMember(key, ip);

        if (flag){
            // 在黑名单中了
            response.getWriter().println("IP is in BlackList,Forbbinden!");
            return;
        }else {
            // 让当前请求继续交给该filter后面的组件进行处理
            // 后面的组件可能包含，其他filter，DispatcherServet，拦截器，Controller
            chain.doFilter(request,response);
        }


    }
}
